<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class DownloadSaiHeImg extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:download_saihe_img';

    /**
     * 临时一次性脚本
     *
     * @var string
     */
    protected $description = '下载赛盒图片';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        try {
            $this->fun();
            echo '执行成功';
        } catch (\Exception $e) {
            //记录错误日志
            $add['job']  = 'DownloadSaiHeImg';
            $add['time'] = time();
            $add['msg']  = $e->getMessage();
            $add['data'] = '';
            DB::table('job_err_log')->insert($add);
        }

    }


    private function fun()
    {
        $list = db::table('saihe_product')
            ->select('id', 'client_sku', 'small_image_url')
            ->groupby('small_image_url')
//            ->where('id', 1)
//            ->limit(10)
//            ->whereIn('id', [17851, 1])
            ->get();

        $count = $list->count();
        $n     = 1;

        foreach ($list as $v) {

            echo $count . '______' . $n . "\n";
            $n++;

            if (!$v->small_image_url || $v->small_image_url == 'Array') {
                continue;
            }


            $url = $v->small_image_url;

            if (strpos($v->small_image_url, '?')) {
                $url = explode('?', $v->small_image_url)[0];
            }

            $clientSku = $v->client_sku;
            if (strstr($clientSku, '/')) {
                $clientSku = str_replace("/", '__', $clientSku);
            }

            $path = storage_path('SaiHeImg' . DIRECTORY_SEPARATOR . $clientSku . '_ID:' . $v->id . '.' . pathinfo($url, PATHINFO_EXTENSION));

            try {
                $this->downloadImg($url, $path);

            } catch (\Exception $exception) {

                echo $count . '______' . $n . '下载失败' . "\n";
                echo $exception->getMessage() . "\n";


                db::table('download_saihe_img_err')->insert([
                    'saihe_product_id' => $v->id,
                    'client_sku'       => $v->client_sku,
                    'small_image_url'  => $v->small_image_url,
                    'err_msg'          => $exception->getMessage(),
                ]);
            }

        }

    }

    private function downloadImg($url, $path)
    {
        $imageContent = file_get_contents($url);

        if ($imageContent !== false) {
            file_put_contents($path, $imageContent);
        } else {
            throw new \Exception("图片保存失败");
        }
    }


}
